import React, { Component } from 'react';

import {
  Switch,
  Redirect,
  Route
} from 'react-router-dom';

import { connect } from 'react-redux';

import {
  Tabbar,
  Header
} from './components';

import routes from './routes';

import './App.less';

import { checkAuth } from './actions/user'

const tabbarRoutes = routes.filter(route => route.title);

const mapState = state => {
  return {
    isSubpage: state.ui.isSubpage,
    isLogin: state.user.isLogin,
    isCheckAuthComplete: state.user.isCheckAuthComplete
  }
}

@connect(mapState, { checkAuth })

export default class App extends Component {

  componentDidMount() {
    this.props.checkAuth();
  }

  render() {
    return (
      this.props.isCheckAuthComplete
      ?
      <div className='app'>
        <Header />
        <div className="main">
          <Switch>
            {
              routes.map(route => {
                return(
                  <Route
                    key={route.path}
                    path={route.path}
                    // component={route.component}
                    render={(props)=> {
                      if(route.isAuthRequired === true && this.props.isLogin === false) {
                        //Redirect组件，Route传参
                        return <Redirect to={{
                          pathname: "/login",
                          state: {
                            from: route.path
                          }
                        }} />
                      }
                      return <route.component {...props} />
                    }}
                  />
                )
              })
            }
            <Redirect exact from='/' to={routes[0].path}/>
            <Redirect to='/404'/>
          </Switch>
        </div>
        {
          (this.props.isSubpage === false) && (
            <div>
              <Tabbar
                routes={tabbarRoutes}
              />
            </div>
          )
        }
      </div>
      :
      null
    )
  }
}
